package com.dengcj.epl.service.wechat.work;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import com.dengcj.epl.cache.TokenCache;
import com.dengcj.epl.entity.WorkWx;

/**
 * @author dengchunjie
 * @Description: 企业微信消息工具类
 * @date 2022/1/19 09:35
 */
public class MessageUtil {

    public MessageUtil(){
        TokenCache.init();
    }

    private String getNewToken(){
        if(StrUtil.isBlank(WorkWx.getCorpId())){
            System.out.println("workwx.setting未配置CorpId");
            return "";
        }

        if(StrUtil.isBlank(WorkWx.getSecret())){
            System.out.println("workwx.setting未配置Secret");
            return "";
        }
        String result = HttpRequest.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + WorkWx.getCorpId() + "&corpsecret=" + WorkWx.getSecret())
                .execute().body();
        JSONObject json = new JSONObject(result);
        String token = json.getStr("access_token");
        if(StrUtil.isBlank(token)){
            System.out.println("获取企业微信接口token失败");
            System.out.println(result);

            return "";
        }
        // 过期时间，单位秒
        Long expires_in = json.getLong("expires_in");
        TokenCache.setWorkWxApiToken(token, expires_in*1000);
        return token;
    }

    private String getToken(){
        String token = TokenCache.getWorkWxApiToken();

        if(StrUtil.isBlank(token)) {
            token = getNewToken();
        }

        return token;
    }

    public boolean sendMessage(String userId, String message){
        String token = getToken();
        if(StrUtil.isBlank(token)){
            return false;
        }
        JSONObject requestJson = new JSONObject();

        JSONObject contentJSON = new JSONObject();
        contentJSON.set("content", message);
        // userid
        requestJson.set("touser", userId);
        requestJson.set("msgtype", "text");
        // agentid
        requestJson.set("agentid", WorkWx.getAgentId());
        // 消息内容
        requestJson.set("text", contentJSON);

        String result = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token)
                .body(requestJson.toString()).execute().body();

        JSONObject resultJSON = new JSONObject(result);
        int errCode = resultJSON.getInt("errcode");
        if(errCode == 40014){//token不合法
            result = HttpRequest.post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+getNewToken())
                    .body(requestJson.toString()).execute().body();
            resultJSON = new JSONObject(result);
            errCode = resultJSON.getInt("errcode");
        }

        if(errCode != 0){
            System.out.println(result);
        }

        return errCode == 0;
    }
}
